<script setup lang="ts">
import {nextTick, onMounted, provide, ref} from 'vue'
import {useRouter} from 'vue-router'

import {accessRecordsDB, movieDB} from '@/data/lowdb.ts'
import {loadMovies} from '@/data/movie'
import {sortByAccessRecords} from '@/data/access_records'

import {AccessRecord, Movie} from '@/data/Dream'
import MovieItem from '@/pages/movie/components/movie-item.vue'
import TextInfo from '@/components/text-info.vue'
import SearchInput from '@/components/search-input.vue'

import {getMovieKey, getMovieTitle} from '@/utils/utils.ts'
import {ElMessage} from 'element-plus'

const router = useRouter()


const movies = ref<Movie[]>()
const movieAccessRecords = ref<Map<string, AccessRecord>>()
provide('movieAccessRecords', movieAccessRecords)

// 从数据库加载页面展示所必须的数据，电影数据和电影访问记录数据
function loadData() {
  movieAccessRecords.value = new Map<string, AccessRecord>(Object.entries(
      accessRecordsDB.read().get('movieAccessRecords').value()
  ))

  movies.value = movieDB.read().value()
      .sort((a: Movie, b: Movie) => {
        return sortByAccessRecords(
            movieAccessRecords.value.get(getMovieKey(a)),
            movieAccessRecords.value.get(getMovieKey(b))
        )
      })
}

// 每次页面挂载完，都重新加载一次数据库的数据
onMounted(() => {
  loadData()
})

// 根据具体的电影文件夹更新电影数据
async function updateDataFromMovieFolder() {
  const message = ElMessage({
    type: 'warning',
    message: 'loading movie...',
    duration: 0,
  })
  await loadMovies()
  loadData()
  message.close()
  ElMessage({
    type: 'success',
    message: 'movies have loaded completed',
  })
}

// 把某部电影显示到屏幕中间
const movieRefs = new Map<string, HTMLElement>

const setMovieRefs = (el: HTMLElement, movie: Movie) => {
  if (el) {
    movieRefs.set(getMovieTitle(movie), el)
  }
}

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      scrollIntoViewMovie()
    }, 300)
  })
})

function scrollIntoViewMovie() {
  // '/dreamVideo?name=%E5%8D%81%E5%85%AB%E7%BD%97%E6%B1%89&year=2003'
  const urlString = router.options.history.state?.forward
  if (!urlString) {
    return
  }
  const url = new URL('http://whatever' + urlString)
  const name = url.searchParams.get('name')
  const year = url.searchParams.get('year')

  const viewItem = movieRefs.get(getMovieTitle(<Movie>{name, year: parseInt(year)}))
  if (viewItem) {
    viewItem.scrollIntoView({behavior: "smooth", block:"center"})
  }
}
</script>

<template>
  <search-input :view-elements="movieRefs"/>

  <div class="movie-container">
    <div class="movie" v-for="movie in movies" :ref="(el) => setMovieRefs(<HTMLElement>el, movie)">
      <movie-item :movie="movie"/>

      <text-info :movieProps="movie"
                 :accessRecords="movieAccessRecords.get(getMovieKey(movie))"
      />
    </div>
  </div>

  <div class="updateDataButton">
    <el-button @click='updateDataFromMovieFolder' type='primary' icon='Refresh' size="large" circle plain></el-button>
  </div>
</template>

<style lang="stylus" scoped>
.movie-container
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  .movie
    background: white;
    border-radius: 5px;
    margin-bottom: 10px;
    border: 2px solid #f4f4f4;
    &:hover
      border: 2px solid #00BE9A;

.updateDataButton
  width max-content
  margin 60px auto 50px
</style>